/*
 * @Date: 2025-06-13 11:12:23
 * @Auth: 463997479@qq.com
 * @LastEditors: 463997479@qq.com
 * @LastEditTime: 2025-09-04 15:38:27
 * @FilePath: \corpus\src\pages\Foundation\Manage\Primitive\index.tsx
 */
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import hooks from '../../hooks/useHooks';

import { getOriginList } from '@/services/ant-design-pro/foundation';
import { Form, message, Popconfirm, Space } from 'antd';
import React, { useEffect, useState } from 'react';
import Priview from '../Priview';
import JsonPriview from '../Priview/json';

type typeCount = {
  name: string;
  countNumber: number;
};
const Primitive: React.FC = () => {
  const {
    actionRef,
    name,
    setName,
    setJsonViewVisible,
    setUrl,
    setType,
    setViewVisible,
    setActiveIndex,
    data,
    id,
    setSelectedKeys,
    levelData,
  } = hooks.useContainer();
  const [count, setCount] = useState(0);
  const [selectedTags, setSelectedTags] = useState<typeCount[]>([]);
  const [selectedTagsType, setSelectedTagsType] = useState<typeCount[]>([]);

  const [form] = Form.useForm();

  useEffect(() => {
    let dataArr = data.map((item) => item.name);
    form.setFieldValue('name', dataArr);
    actionRef.current?.reload();
  }, [data]);
  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      title: '序号',
    },
    {
      title: '原始文件名称',
      dataIndex: 'fileName',
      ellipsis: true,
    },
    {
      title: '语料内容',
      dataIndex: 'fileContent',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return (
          <>
            <span title={record.fileContent}>{record.fileContent}</span>
          </>
        );
      },
    },
    {
      title: '文件类型',
      dataIndex: 'fileFormat',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },

    {
      title: '数源部门',
      dataIndex: 'sourceOrg',
      ellipsis: true,
      width: 162,
    },

    {
      title: '公布日期',
      dataIndex: 'fbrq',
      ellipsis: true,
      hideInSearch: true,
      width: 146,
    },

    {
      title: '操作',
      width: 100,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: any) => [
        <Popconfirm
          key={1}
          title="预览文件"
          description={`预览文件`}
          onConfirm={() => {
            setUrl(record.yklRel);
            setType(record.fileFormat === 'doc' ? 'docx' : record.fileFormat);
            if (record.fileFormat === 'json' || record.fileFormat === 'txt') {
              setJsonViewVisible(true);
            } else if (
              record.fileFormat === 'docx' ||
              record.fileFormat === 'pdf' ||
              record.fileFormat === 'doc'
            ) {
              setViewVisible(true);
            } else {
              message.success('暂不支持预览');
            }
          }}
          onCancel={() => {}}
          okText="确认"
          cancelText="取消"
        >
          {<a>预览</a>}
        </Popconfirm>,
        <Popconfirm
          key={2}
          title="下载文件"
          description={`确认下载当前文件？`}
          onConfirm={() => {
            window.open(`${window.location.origin}/corpus/base/getFile?yklRel=${record.yklRel}`);
          }}
          onCancel={() => {}}
          okText="确认"
          cancelText="取消"
        >
          {<a>下载</a>}
        </Popconfirm>,
      ],
    },
  ];
  /**
   *
   * @param tag 点击筛选条件
   * @param checked
   */
  const handleChange = (tag: typeCount, checked: boolean) => {
    const nextSelectedTags = checked
      ? [...selectedTags, tag]
      : selectedTags.filter((t) => t !== tag);
    setSelectedTags(nextSelectedTags);
    const arr = nextSelectedTags?.map((item: typeCount) => item?.name);
    form.setFieldValue('name', arr);
    console.log(form.getFieldValue('name'));
  };
  const handleChangeType = (tag: typeCount, checked: boolean) => {
    const nextSelectedTags = checked
      ? [...selectedTagsType, tag]
      : selectedTagsType.filter((t) => t !== tag);
    setSelectedTagsType(nextSelectedTags);
    const arr = nextSelectedTags?.map((item: typeCount) => item?.name);
    form.setFieldValue('type', arr);
    console.log(form.getFieldValue('type'));
  };
  return (
    <>
      <ProTable<API.RuleListItem, API.PageParams>
        toolBarRender={() => []}
        rowKey="key"
        actionRef={actionRef}
        // tableExtraRender={(_, dataBak) => {
        //   return (
        //     <Card bodyStyle={{ padding: '10.0px' }}>
        //       <div style={{ marginLeft: '10.0px' }}>
        //         <Form labelCol={{ span: 1 }} wrapperCol={{ span: 24 }} form={form}>
        //           <Form.Item label="分级" name="name">
        //             {levelData.map((tag) => (
        //               <Tag.CheckableTag
        //                 key={tag.name}
        //                 checked={selectedTags.indexOf(tag) > -1}
        //                 onChange={(checked) => handleChange(tag, checked)}
        //               >
        //                 {tag.name} ({tag.countNumber}个)
        //               </Tag.CheckableTag>
        //             ))}
        //           </Form.Item>

        //           <Form.Item label="分类" name="password">
        //             {data.map((tag) => (
        //               <Tag.CheckableTag
        //                 key={tag.name}
        //                 checked={selectedTagsType.indexOf(tag) > -1}
        //                 onChange={(checked) => handleChangeType(tag, checked)}
        //               >
        //                 {tag.name} ({tag.countNumber}个)
        //               </Tag.CheckableTag>
        //             ))}
        //           </Form.Item>
        //         </Form>
        //       </div>
        //     </Card>
        //   );
        // }}
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params: any,
        ) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改

          const msg = await getOriginList({
            ...params,
            sourceOrg: name,
            // fileType1: form.getFieldValue('name'),
            knowledgeId: id,
          });
          setCount(msg.total);
          return {
            data: msg.data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: msg.total,
          };
        }}
        headerTitle={
          <Space align="center">
            <span style={{ fontSize: '14.0px' }}>原始语料文件总数：{count}条</span>
          </Space>
        }
        onReset={() => {
          setName('');
          setActiveIndex('');
          setSelectedKeys([]);
          actionRef.current?.reset();
        }}
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          showSizeChanger: true,
          defaultPageSize: 10,
        }}
        columns={columns}
      />
      <Priview />
      <JsonPriview />
    </>
  );
};

export default Primitive;
